import os
import time

import cv2
import numpy as np
import uiautomator2 as u2


class HongBaoPosition:

    @classmethod
    def get_location(cls, image_path, lower, upper):
        # 读取图像
        image = cv2.imread(image_path)

        # 转换颜色空间到HSV
        hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

        lower_green = np.array(lower)
        upper_green = np.array(upper)

        # 创建掩码
        mask = cv2.inRange(hsv, lower_green, upper_green)

        # 开运算
        k = np.ones((10, 10), np.uint8)
        r = cv2.morphologyEx(mask, cv2.MORPH_OPEN, k, 5)

        # 获取最小矩形
        contours, hierarchy = cv2.findContours(r, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        container = []
        for i in range(len(contours)):
            area = cv2.contourArea(contours[i], oriented=False)
            if area > 10000:
                container.append(i)

        if not len(container):
            return None, None, None, None

        if len(container) == 1:
            x, y, w, h = cv2.boundingRect(contours[container[0]])
            return x, y, w, h
        else:
            max_y = 0
            min_i = 0
            for i in container:
                x, y, w, h = cv2.boundingRect(contours[i])
                if y > max_y:
                    max_y = y
                    min_i = i
            x, y, w, h = cv2.boundingRect(contours[container[min_i]])
            return x, y, w, h


class QiangHongBao:
    APP_NAME = 'com.tencent.mm'
    device = None
    activity = 'com.tencent.mm.ui.LauncherUI'

    def __init__(self):
        try:
            self.device = u2.connect('emulator-5554')
            print(self.device.info)
        except Exception as e:
            os.system("adb shell /data/local/tmp/atx-agent server -d --stop")
            print("未连接到雷电模拟器")

    def screenshot(self, image_path):
        self.device.screenshot(image_path)

    def click_position(self, x, y):
        self.device.click(x, y)

    def press_back(self):
        self.device.press("back")


def main():
    LeiDian_Server = QiangHongBao()
    image_path = "./temp.png"
    while True:
        try:
            LeiDian_Server.screenshot(image_path)

            # 检测是否发现红包
            x, y, w, h = HongBaoPosition.get_location(image_path, lower=[15, 100, 100], upper=[35, 255, 255])
            print("红包检测", x, y, w, h)
            if x and y:
                LeiDian_Server.click_position(x, y)

            # 检测是否已经点开红包
            x, y, w, h = HongBaoPosition.get_location(image_path, lower=[0, 120, 70], upper=[10, 255, 255])
            print("位置检测", x, y, w, h)
            if x is not None:
                if x:
                    x = x + int(w / 2)
                    y = y + int(h * 4 / 5)
                    LeiDian_Server.click_position(x, y)
                else:
                    LeiDian_Server.press_back()

            if x is not None:
                x = x + int(w / 2)
                y = y + int(h * 6 / 5)
                LeiDian_Server.click_position(x, y)

        except Exception as e:
            continue
        finally:
            time.sleep(0.3)


if __name__ == '__main__':
    main()
